/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 31.07.2005
 *
 *************************************************/
package fightplan.ui;

import java.awt.Color;
import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import fightplan.business.Validation;
import fightplan.business.ValueValidation;

@SuppressWarnings("serial")
public class BeanPropertyTableCellRenderer extends DefaultTableCellRenderer {
	private String property;
	private Validation validation;

	public BeanPropertyTableCellRenderer() {
	}

	public BeanPropertyTableCellRenderer(String property) {
		this.property = property;
	}

	public BeanPropertyTableCellRenderer(Validation validation) {
		this.validation = validation;
	}

	public BeanPropertyTableCellRenderer(String property, Validation validation) {
		this.property = property;
		this.validation = validation;
	}

	public BeanPropertyTableCellRenderer(String property, int alignment) {
		this.property = property;
		setHorizontalAlignment(alignment);
	}

	public BeanPropertyTableCellRenderer(String property, int alignment, Validation validation) {
		this.property = property;
		this.validation = validation;
		setHorizontalAlignment(alignment);
	}

	@Override
	public Component getTableCellRendererComponent(JTable table, Object object, boolean isSelected, boolean hasFocus,
			int row, int column) {
		Object value = property != null ? BeanListTableModel.getPropertyValue(object, property) : object;
		JComponent component = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
				row, column);
		component.setOpaque(true);
		if (!isSelected && validation != null) {
			Object validatable;
			if (validation instanceof ValueValidation) {
				validatable = value;
			} else if (table.getModel() instanceof BeanListTableModel) {
				BeanListTableModel<?> tableModel = (BeanListTableModel<?>) table.getModel();
				validatable = tableModel.getList().get(row);
			} else {
				return component;
			}
			Color validationColor = validation.validationColor(validatable);
			if (validationColor != null) {
				component.setBackground(validationColor);
			} else {
				component.setBackground(Color.WHITE);
			}
			component.setToolTipText(validation.validationText(validatable));
		}
		return component;
	}

}
